<template>
	<el-dialog v-model="model" title="修改暱稱" width="450px">
		<el-form>
			<el-form-item :error="errorMsg">
				<el-input
					v-model.trim="nickName"
					placeholder="請輸入新暱稱"
					@change="errorMsg = null"
				/>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button :loading="submitting" type="primary" @click="handleSave">保存</el-button>
		</template>
	</el-dialog>
</template>
<script setup>
import { userStore } from '~/composables/store/modules/user';

const model = defineModel({ type: Boolean });
const store = userStore();
const nickName = ref(null);
const submitting = ref(false);
const errorMsg = ref(null);

function handleCancel() {
	model.value = false;
}

async function handleSave() {
	if (!nickName.value) {
		errorMsg.value = '新昵稱不得為空！';
		return;
	}
	submitting.value = true;
	try {
		const body = {
			nickname: nickName.value,
		};
		await store.updateUserInfoAction(body);
		model.value = false;
	} finally {
		submitting.value = false;
	}
}

watch(
	() => model.value,
	now => {
		if (now) {
			nickName.value = store.profile.nickname;
		} else {
            errorMsg.value = null;
        }
	}
);
</script>
